package com.project.plus.util;

import com.google.code.kaptcha.Constants;

import javax.servlet.http.HttpServletRequest;

/**
 * @ClassName CodeUtil
 * @Description TODO
 * @Author Invoker
 * @Date 2020/9/27 15:12
 * @Version 1.0
 */
public class CodeUtil {

    /**
     * 将获取到的前端参数转为string类型
     * @param request
     * @param key
     * @return
     */
    public static String getString(HttpServletRequest request,String key){
        try {
            
            String result = request.getParameter(key);
            if (result!=null){
                result = result.trim();
            }
            if ("".equals(result)) {
                return null;
            }
            return result;
        }catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 验证验证码是否正确
     * @param request
     * @return
     */
    public static boolean checkVerifyCode(HttpServletRequest request){
        
        //获取生成的验证码
        String verifyCodeSys = request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY).toString();
        //获取输入的验证码
        String verifyCodeUser = CodeUtil.getString(request,"verifyCodeUser");

        System.out.println("verifyCodeSys:"+verifyCodeSys);
        System.out.println("verifyCodeUser:"+verifyCodeUser);
        if (verifyCodeUser==null || !verifyCodeSys.equals(verifyCodeUser)) {
            return false;
        }else{
            return true;
        }
    }
}
